package com.ys.controller.api.storage;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.ys.config.MenuId;
import com.ys.entity.storage.TccOnlineAssembleError;
import com.ys.entity.sys.YsCol;
import com.ys.enume.finance.TcwExpenseSettleReturnUsedEnum;
import com.ys.service.storage.TccOnlineAssembleErrorService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService;
import com.ys.util.CheckUtil;
import com.ys.util.ExportExcelUtils;
import com.ys.util.ToolUtil;
import com.ys.util.admin.ConditionUtil;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
import java.util.Map;

/**
 * 线上组装报错单
 */
@Controller
@RequestMapping("/api/inter/tccOnlineAssembleError")
public class ApiInterTccOnlineAssembleErrorController {
    private static final Logger logger = LoggerFactory.getLogger(ApiInterTccOnlineAssembleErrorController.class);

    @Autowired
    private CommonApiService<TccOnlineAssembleError> commonApiService;

    @Autowired
    private TccOnlineAssembleErrorService tccOnlineAssembleErrorService;

    //菜单id
    private Long menuId = MenuId.TCC_OnlineAssembleError;

    @Autowired
    private CheckUtil checkUtil;

    //权限字符
    private final String PERMISSIONS_VIEW = "tccOnlineAssembleError:view";
    private final String PERMISSIONS_ERROR_HANDL = "tccOnlineAssembleError:errorHandle";

    //private final String PERMISSIONS_NOT_HANDLE = "tccOnlineAssembleError:notHandle";
    //private final String PERMISSIONS_REPAIR_SEND = "tccOnlineAssembleError:repairSend";
    //private final String PERMISSIONS_PURCHASE_PAY = "tccOnlineAssembleError:purchasePay";
    //private final String PERMISSIONS_PURCHASE_BACK = "tccOnlineAssembleError:purchaseBack";

    /**
     * 设置查询的cond的sql设置
     * @param cond
     * @return
     */
    public TccOnlineAssembleError setSeachSql(TccOnlineAssembleError cond) throws Exception{
        cond
                .addField("A.HandleStatus AS _ys_handleStatus")//状态

                .addLeftJoin("TCC_OnlineAssembleErrorItem B ON A.Bid = B.Pbid")//子列表
                .addField("B.InStorageBid AS inStorageBid")//入库单号
                .addField("B.LogisticsMode AS logisticsMode")//物流方式
                .addField("B.TrackingNumber AS trackingNumber")//物流单号
                .addField("B.SubCode AS subCode")//子件编码
                .addField("B.SubAssembleLostNum AS subAssembleLostNum")//子件缺失数量
                .addField("B.SubAmount AS subAmount")//子件采购单价
                .addField("B.SubAssembleLostNum * B.SubAmount AS subLostNum")//子件缺失金额

                //费用结算返还单被调用详情表
                .addLeftJoin("TCW_ExpenseSettleReturnUsed C ON C.UsedSourceId = A.Id AND C.UsedSourceType ="+ TcwExpenseSettleReturnUsedEnum.SourceType.TCC_OnlineAssembleError.value)
                .addField("C.ExpenseSettleReturnBid AS expenseSettleReturnBid")//费用结算返还单单号
                .addField("C.ReturnAmountTotal AS returnAmountTotal")//返还总金额

                .addLeftJoin("TCC_OfflineAssemble D ON D.Id = A.AssembleId")//组装单
                .addField("D.Bid AS assembleBid")//组装单号
                .addField("D.ParentAssembleNumber AS parentAssembleNumber")//母件组装数量(实际)
                .addField("FORMAT(D.AuditTime, 'yyyy-MM-dd HH:mm:ss') AS assembleAuditTime")//审核时间



                .addLeftJoin("TCG_PurchaseByOrder E ON E.Bid = A.PurchaseOrderBid")//采购订单表
                .addField("E.AliOrderNumber AS aliOrderNumber")//1688订单编号
                .addField("E.PlanBid AS planBid")//采购计划单号


                .addLeftJoin("TCG_PurchasePlanGoods F ON F.Id = E.PurchasePlanGoodsId")//采购计划单母件表信息
                .addField("F.SpAmount AS spAmount")//采购数量
                .addField("F.SpBm AS spBm")//采购数量


                .addLeftJoin("TCG_PurchaseByOrderSon G ON G.Pid = E.Id AND G.SubCode = B.SubCode")//采购订单子表

                .addLeftJoin("TCG_PurchaseByPlanSon H ON H.Id = G.PurchasePlanSonId ")//采购计划单子表
                .addField("H.SubName AS subName")//子件商品名称
                .addField("H.SubAmount AS subAmount")//子件BOM数量
                .addField("H.StoreAmount AS storeAmount")//子件入库数量

                .addLeftJoin("TCC_OfflineAssembleItem I ON I.Id = B.AssembleItemId ")//组装单子表
                .addField("I.SubRealStorageNum AS subRealStorageNum")//子件组装数量
                .addField("I.SubAssembleLeftNum AS subAssembleLeftNum")//子件剩余数量




                .addLeftJoin("TCG_OfflinePurchaseInStorage J on J.id = I.offlinePurchaseStorageId")
                .addField("J.ProductImgOne AS productImgOne")//商品图片1
                .addField("J.ProductImgTwo AS productImgTwo")//商品图片2
                .addField("J.ProductImgThree AS productImgThree")//商品图片3
                .addField("J.ProductName AS productName")//商品名称
                //.addField("J.bid offlinePurchaseInStorageBid")//采购入库单号

                .addLeftJoin("THR_OperateCompanyApply K ON K.Vgsbm = J.Vgsbm ")//运营公司管理表
                .addField("K.Vgsjc AS vgsjc")//采购公司简称
                .addField("K.Vgsbm AS vgsbm")//采购公司编码

                .addLeftJoin("TS_UserChange L on L.Id = K.OperatorChangeId")
                .addField("L.UserId operatorUserId")//运营人工号
                .addField("L.UserName operatorUserName")//运营人

                .setStatus(1)

                ;

        //排序
        cond.setOrderby("A.Bid DESC");
        //权限
        cond = commonApiService.dataAuth(menuId, cond);
        return  cond;
    }


    /**
     * 查询
     */
    @RequiresPermissions(PERMISSIONS_VIEW)
    @RequestMapping("/search")
    @ResponseBody
    public LayuiTableVoJA search(@ModelAttribute TccOnlineAssembleError cond,String conditions){
        try {
            cond = setSeachSql(cond);
            String handleStatus = ConditionUtil.getConditionValue(conditions, "_ys_handleStatus");//状态
            if (handleStatus != null && !"".equals(handleStatus)) {
                if(!"-1".equals(handleStatus)){
                    cond.where("A.HandleStatus  = "+handleStatus);
                }
            }
            return commonApiService.searchLay(cond);
        }catch (Exception e){
            logger.error("查询出错：",e.getMessage(),e);
            LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
            tableVoJA.setCode(1);
            tableVoJA.setMsg("查询出错，请稍后重试！");
            return tableVoJA;
        }
    }

    /**
     * 导出
     */
    @RequestMapping("/export")
    @ResponseBody
    public R export(@ModelAttribute TccOnlineAssembleError cond,String conditions){
        try {
            cond.setPage(0).setSize(999999);
            cond = setSeachSql(cond);

            //获取菜单字段数据
            List<YsCol> listField = new YsCol()
                    .setMenuId(menuId)
                    .setFrontShow(1)
                    .setOrderby("A.SortNo asc")
                    .queryList();
            //获取数据
            List<Map<String, Object>> listData = cond.queryMap();

            //处理数据
            ExportExcelUtils<TccOnlineAssembleError> util = new ExportExcelUtils<>(new TccOnlineAssembleError());
            String toFilePath = util.exportExcel(listData, listField, "线上组装报错单");
            UploadService.UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
            return R.ok(dto.getUrl());
        }catch (Exception e){
            logger.error("导出出错：",e.getMessage(),e);
            return R.error("导出失败，请稍后重试！");
        }
    }

    /**
     * 不处理
     */
    @RequiresPermissions(PERMISSIONS_ERROR_HANDL)
    @RequestMapping("/notHandle")
    @ResponseBody
    public R notHandle( @RequestParam Map<String, Object> params){
        try {
            if(checkUtil.isNullByObject(params.get("errorCause"))){
                return R.error("请输入不处理的原因");
            }
            String errorCause = params.get("errorCause").toString();
            String choooseDatas = params.get("choooseDatas").toString();
            JSONArray detailJA = JSON.parseArray(choooseDatas);
            //根据采购订单号去重
            List<Map<String, Object>> groupsByJSONArray = ToolUtil.groupsByJSONArray(detailJA, e->e.get("purchaseOrderBid")!=null?e.get("purchaseOrderBid").toString():"");

            int doCount = 0;
            StringBuffer resMsg = new StringBuffer();
            for (int i = 0; i < groupsByJSONArray.size(); i++) {
                Map<String, Object> detailJO = groupsByJSONArray.get(i);
                //处理
                R res = tccOnlineAssembleErrorService.notHandle(detailJO.get("purchaseOrderBid").toString(),errorCause);
                if(res.getCode()==0){
                    doCount ++;
                }else{
                    resMsg.append("单号：")
                            .append(detailJO.get("bid")!=null?detailJO.get("bid"):"")
                            .append("；")
                            .append(res.getMsg())
                            .append("</br>");
                }
            }
            resMsg = new StringBuffer().append("成功操作").append(doCount).append("条数据</br>").append(resMsg);
            return R.ok(resMsg);
        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error("系统出错");
        }
    }


    /**
     * 补发货
     */
    @RequiresPermissions(PERMISSIONS_ERROR_HANDL)
    @RequestMapping("/repairSend")
    @ResponseBody
    public R repairSend(@RequestParam Map<String, Object> params){
        try {
            if(checkUtil.isNullByObject(params.get("logisticsMode"))){
                return R.error("请输入物流方式");
            }
            if(checkUtil.isNullByObject(params.get("trackingNumber"))){
                return R.error("请输入物流单号");
            }
            String logisticsMode = params.get("logisticsMode").toString();
            String trackingNumber = params.get("trackingNumber").toString();
            String choooseDatas = params.get("choooseDatas").toString();
            JSONArray detailJA = JSON.parseArray(choooseDatas);
            //根据采购订单号去重
            List<Map<String, Object>> groupsByJSONArray = ToolUtil.groupsByJSONArray(detailJA, e->e.get("purchaseOrderBid")!=null?e.get("purchaseOrderBid").toString():"");

            int doCount = 0;
            StringBuffer resMsg = new StringBuffer();
            for (int i = 0; i < groupsByJSONArray.size(); i++) {
                Map<String, Object> detailJO = groupsByJSONArray.get(i);
                //处理
                R res = tccOnlineAssembleErrorService.repairSend(detailJO.get("purchaseOrderBid").toString(),logisticsMode,trackingNumber);
                if(res.getCode()==0){
                    doCount ++;
                }else{
                    resMsg.append("单号：")
                            .append(detailJO.get("bid")!=null?detailJO.get("bid"):"")
                            .append("；")
                            .append(res.getMsg())
                            .append("</br>");
                }
            }
            resMsg = new StringBuffer().append("成功操作").append(doCount).append("条数据</br>").append(resMsg);
            return R.ok(resMsg);
        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error("系统出错");
        }
    }



    /**
     * 采购赔偿
     */
    @RequiresPermissions(PERMISSIONS_ERROR_HANDL)
    @RequestMapping("/purchasePay")
    @ResponseBody
    public R purchasePay(@RequestParam Map<String, Object> params){
        try {
            if(checkUtil.isNullByObject(params.get("expenseSettleReturnItemId"))){
                return R.error("费用结算返还单信息为空");
            }
            Long expenseSettleReturnItemId = Long.parseLong(params.get("expenseSettleReturnItemId").toString());
            String choooseDatas = params.get("choooseDatas").toString();
            JSONArray detailJA = JSON.parseArray(choooseDatas);
            //根据采购订单号去重
            List<Map<String, Object>> groupsByJSONArray = ToolUtil.groupsByJSONArray(detailJA, e->e.get("purchaseOrderBid")!=null?e.get("purchaseOrderBid").toString():"");

            int doCount = 0;
            StringBuffer resMsg = new StringBuffer();
            for (int i = 0; i < groupsByJSONArray.size(); i++) {
                Map<String, Object> detailJO = groupsByJSONArray.get(i);
                //处理
                R res = tccOnlineAssembleErrorService.purchasePay(detailJO.get("purchaseOrderBid").toString(),expenseSettleReturnItemId);
                if(res.getCode()==0){
                    doCount ++;
                }else{
                    resMsg.append("单号：")
                            .append(detailJO.get("bid")!=null?detailJO.get("bid"):"")
                            .append("；")
                            .append(res.getMsg())
                            .append("</br>");
                }
            }
            resMsg = new StringBuffer().append("成功操作").append(doCount).append("条数据</br>").append(resMsg);
            return R.ok(resMsg);
        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error("系统出错");
        }
    }

    /**
     * 采购退款
     */
    @RequiresPermissions(PERMISSIONS_ERROR_HANDL)
    @RequestMapping("/purchaseBack")
    @ResponseBody
    public R purchaseBack(String backBid, String choooseDatas){
        try {
            if(checkUtil.isNullByObject(backBid)){
                return R.error("线上采购退货单单号为空");
            }
            JSONArray detailJA = JSON.parseArray(choooseDatas);
            //根据采购订单号去重
            List<Map<String, Object>> groupsByJSONArray = ToolUtil.groupsByJSONArray(detailJA, e->e.get("purchaseOrderBid")!=null?e.get("purchaseOrderBid").toString():"");

            int doCount = 0;
            StringBuffer resMsg = new StringBuffer();
            for (int i = 0; i < groupsByJSONArray.size(); i++) {
                Map<String, Object> detailJO = groupsByJSONArray.get(i);
                //处理
                R res = tccOnlineAssembleErrorService.purchaseBack(detailJO.get("purchaseOrderBid").toString(),backBid);
                if(res.getCode()==0){
                    doCount ++;
                }else{
                    resMsg.append("单号：")
                            .append(detailJO.get("bid")!=null?detailJO.get("bid"):"")
                            .append("；")
                            .append(res.getMsg())
                            .append("</br>");
                }
            }
            resMsg = new StringBuffer().append("成功操作").append(doCount).append("条数据</br>").append(resMsg);
            return R.ok(resMsg);
        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error("系统出错");
        }
    }








}